import java.io.*;
import java.net.*;
import java.util.*;

public class Server {

    private static final int PORT = 12345; // 服务器监听端口
    private static Set<PrintWriter> clientWriters = new HashSet<>();

    public static void main(String[] args) {
        System.out.println("聊天服务器启动，等待连接...");

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            while (true) {
                new ClientHandler(serverSocket.accept()).start();  // 每有一个新的客户端连接，启动一个线程
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 处理每个客户端的连接
    private static class ClientHandler extends Thread {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                // 设置输入输出流
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                synchronized (clientWriters) {
                    clientWriters.add(out);  // 将新的客户端输出流添加到集合中
                }

                // 处理客户端发送的消息
                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("收到消息: " + message);
                    broadcast(message);  // 将消息广播给所有客户端
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                synchronized (clientWriters) {
                    clientWriters.remove(out);  // 客户端断开连接时，从集合中移除该客户端
                }
            }
        }

        // 广播消息给所有客户端
        private void broadcast(String message) {
            synchronized (clientWriters) {
                for (PrintWriter writer : clientWriters) {
                    writer.println(message);
                }
            }
        }
    }
}

